#include "ObjectManager.h"

ObjectManager* ObjectManager::instance=NULL;

ObjectManager::ObjectManager(){
}

ObjectManager::~ObjectManager(){}

void ObjectManager::destroy(){
	if(ObjectManager::instance!=NULL)
		delete ObjectManager::instance;
}

void ObjectManager::generateAllTextures(std::list<MapList*>& elements){
	std::list<MapList*>::iterator it;
	std::string type;

	TextureFactory *textureFactory = TextureFactory::getInstance();

	for(it=elements.begin();it!=elements.end();++it){
		MapList* elementMap = (MapList*)(*it);
		std::map<string,CustomizedMap>::iterator elementIt;
		type = elementMap->getType();
		try{
			ObjectType objType = ObjectTypeUtils::getObjectTypeByString(type);
		
			if(ObjectTypeUtils::isTexture(objType)){
				if(elementMap->isValid()){
					try{
						Texture *texture = textureFactory->getTexture(elementMap);
						TextureContainer::getInstance()->addTexture(texture);
					}catch(InvalidTextureException &e){
						Logger::get_instance()->log(e);
					}
					catch(IdAlreadyExistsException &e){
						Logger::get_instance()->log(e);
					}
				}else
					Logger::get_instance()->log("No son validos los atributos seteados para la textura");	
			}
		}catch(InvalidObjectTypeException &e){
			Logger::get_instance()->log(e);
			delete elementMap;
		}
	}
}


void ObjectManager::generateAllFigures(std::list<MapList*>& elements){
	std::list<MapList*>::iterator it;
	std::string type;

	FigureFactory *figureFactory = FigureFactory::getInstance();

	for(it=elements.begin();it!=elements.end();++it){
		MapList* elementMap = (MapList*)(*it);
		std::map<string,CustomizedMap>::iterator elementIt;
		type = elementMap->getType();
		try{
			ObjectType objType = ObjectTypeUtils::getObjectTypeByString(type);
			if(ObjectTypeUtils::isFigure(objType)){
				if(elementMap->isValid()){
					try{
						Figure * figure = figureFactory->getFigure(objType,elementMap);
						FigureContainer::getInstance()->addFigure(figure);
						Logger::get_instance()->log(figure);
					}catch(InvalidFigureException &e){
						Logger::get_instance()->log(e);
					}
					catch(IdAlreadyExistsException &e){
						Logger::get_instance()->log(e);
					}
				}else{
					std::string msj ="No son validos los atributos seteados para la figura: ";
					Logger::get_instance()->log(msj+ elementMap->getType());
				}
			}
		}catch(InvalidObjectTypeException &e){	
			//	Logger::get_instance()->log(e);
		}
	}
}

void ObjectManager::generateElements(std::list<MapList*>& elements){	
	generateAllTextures(elements);
	DefaultParameterManager::getInstance()->manageGeneralTag(elements);
	generateAllFigures(elements);
}


ObjectManager* ObjectManager::getInstance(){
	if(ObjectManager::instance==NULL)
		ObjectManager::instance = new ObjectManager();
	return ObjectManager::instance;
}